﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

namespace NHTrace
{
  public class HtmlMessageRenderer : IMessageRenderer
  {
    private StringBuilder _preContent;
    private StringBuilder _postContent;
    private WebBrowserEx _browser;

    public HtmlMessageRenderer(WebBrowserEx browser, string templateFile)
    {
      _browser = browser;
      string template = File.ReadAllText(templateFile);
      template = template.Replace("{templatePath}", Path.GetDirectoryName(templateFile));

      string preContent = template.Substring(0, template.IndexOf("{content}"));
      string postContent = template.Substring(template.IndexOf("{content}") + "{content}".Length);

      _preContent = new StringBuilder(preContent);
      _postContent = new StringBuilder(postContent);
    }

    private string getHtml(StringBuilder messages)
    {
      return _preContent.ToString() + messages.ToString() + _postContent.ToString();
    }

    public void Render(IList<string> messages)
    {
      StringBuilder sb = new StringBuilder();
      foreach (var m in messages)
        sb.AppendLine(m);

      _browser.Parent.BeginInvoke((ThreadStart)delegate()
      {
        _browser.DocumentText = getHtml(sb); 
      });
    }
  }
}